import 'package:flutter/services.dart';
import 'package:zrjz/router/page_router.dart';

class MyRouterHistoryManager {
  static final MyRouterHistoryManager _instance = MyRouterHistoryManager._internal();

  factory MyRouterHistoryManager() {
    return _instance;
  }

  MyRouterHistoryManager._internal();

  final List<String?> _routeNames = [];

  // 自己记录路由栈 - 存入
  void putRouterByName(String? routeName) {
    if (routeName != null) {
      _routeNames.add(routeName);
      try2SetVerticalOrientation(routeName);
    }
  }

  // 自己记录路由栈 - 移除
  void removeRouterByName(String? routeName) {
    if (routeName != null && _routeNames.contains(routeName)) {
      _routeNames.remove(routeName);
      try2RestoreOrientation(routeName);
    }
  }

  //尝试设置只竖屏方向展示页面
  void try2SetVerticalOrientation(String routeName) {
    if (RouterPath.onlyVerticalOrientationRouterName.contains(routeName)) {
      //如果包含白名单路由，需要设置垂直
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
      ]);
    }
  }

  //尝试设置横竖屏方向展示页面
  void try2RestoreOrientation(String routeName) {
    if (RouterPath.onlyVerticalOrientationRouterName.contains(routeName)) {
      //如果包含白名单路由，需要恢复全局
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.landscapeLeft,
        DeviceOrientation.landscapeRight,
      ]);
    }
  }

  //获取到全部的RouterName数组
  List<String?> get routeNames => _routeNames;

  //查询当前栈中是否存在指定的路由名称
  bool isRouteExist(String routeName) {
    return _routeNames.contains(routeName);
  }

  // 只是检查栈顶
  bool isTopRouteExist(String routeName) {
    if (_routeNames.isNotEmpty) {
      return _routeNames.last == routeName;
    } else {
      return false;
    }
  }
}
